import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import '../services/att_service.dart';

/// ATT状态Provider
/// 提供当前的App Tracking Transparency权限状态
final attStatusProvider = FutureProvider<TrackingStatus>((ref) async {
  return await ATTService.getCurrentStatus();
});

/// ATT状态通知器Provider
/// 允许手动刷新ATT状态
final attStatusNotifierProvider = StateNotifierProvider<ATTStatusNotifier, AsyncValue<TrackingStatus>>((ref) {
  return ATTStatusNotifier();
});

class ATTStatusNotifier extends StateNotifier<AsyncValue<TrackingStatus>> {
  ATTStatusNotifier() : super(const AsyncValue.loading()) {
    _loadStatus();
  }

  /// 加载当前ATT状态
  Future<void> _loadStatus() async {
    try {
      final status = await ATTService.getCurrentStatus();
      state = AsyncValue.data(status);
    } catch (e, stack) {
      state = AsyncValue.error(e, stack);
    }
  }

  /// 刷新ATT状态
  Future<void> refreshStatus() async {
    state = const AsyncValue.loading();
    await _loadStatus();
  }

  /// 请求ATT权限
  Future<TrackingStatus> requestPermission() async {
    state = const AsyncValue.loading();
    try {
      final status = await ATTService.requestTrackingPermission();
      state = AsyncValue.data(status);
      return status;
    } catch (e, stack) {
      state = AsyncValue.error(e, stack);
      rethrow;
    }
  }

  /// 检查是否需要请求权限
  Future<bool> shouldRequestPermission() async {
    return await ATTService.shouldRequestPermission();
  }

  /// 获取状态描述
  String getStatusDescription(TrackingStatus status) {
    return ATTService.getStatusDescription(status);
  }
} 